use std::any::Any;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

#[test]
fn refcell_test() {
    let tt = RefCell::new(String::new());
    tt.borrow_mut().push_str("test");
    let str = tt.borrow().as_str();
}

fn test(refValue: RefCell<String>) -> String {
    let t = refValue.borrow();
    t.to_string()
}

struct RpcData {
    data: Rc<RefCell<HashMap<String, Box<dyn Any>>>>,
}

impl RpcData {

    pub fn new() -> RpcData {
        RpcData {
            data: Rc::new(RefCell::new(HashMap::new())),
        }
    }

    pub fn insert(&mut self, key: &str, value: Box<dyn Any>) {
        self.data.borrow_mut().insert(key.to_string(), Box::new(value));
    }

    /// 问题： 对象超出什么周期范围
    pub fn get(&self, key: &str) -> Option<&Box<dyn Any>> {
        let bt = self.data.borrow();
        let t = bt.get(key);
        // return t;  // 问题点
        None
    }

    pub fn get_and_handle<R, F: Fn(Option<&mut Box<dyn Any>>)-> R>(&mut self, key: &str, f: F)->R {
        let mut tt = self.data.borrow_mut();
        let t = tt.get_mut(key);
        f(t)
    }
}